#!/bin/sh
wan_port=$(cat /etc/config/wanport)
lan_port=$(cat /etc/config/lanport)
mgmt_vlan=$(cat /etc/config/mgmtvlan)

case $1 in
  start)
    hostname GFiberONU

    echo "WAN port: $wan_port"
    echo "LAN port: $lan_port"
    echo "MGMT VLAN: $mgmt_vlan"
    echo
    echo "Disabling accepting RAs on pon0"
    sysctl -w net.ipv6.conf.pon0.accept_ra=0
    sysctl -w net.ipv6.conf.pon0.accept_ra_defrtr=0
    sysctl -w net.ipv6.conf.pon0.accept_ra_pinfo=0

    echo "Starting WAN."
    # Configure dhclient with the right hostname etc.
    setup-dhclient
    echo "Starting interface."
    ifup "$wan_port"
    echo "Configuring data path."
    if [ -z "$lan_port" ]; then
      lan_arg=""
    else
      lan_arg="-l $lan_port"
    fi
    if runnable start_sycl; then
      echo "Starting sycl"
      ip link add link pon0 name man type vlan id "$mgmt_vlan"
      ifup man
      rdiscloop 2>&1 | logos rdiscloop &
      start_sycl 2>&1 | \
        grep --line-buffered -v 'apm_avc_main_loop: type [7-9], param1 0, get state Failed' | logos sycl &
    fi

    # Start the optical watchdog.
    babysit 60 opticalwatchdog 2>&1 | logos opticalwatchdog &
    ;;
  stop)
    echo -n "Stopping WAN..."
    if [ -n "$mgmt_vlan" ]; then
      ifdown man
      ip link del man
    fi
    ifdown "$wan_port"
    pkill -f rdiscloop
    pkill -f sycl
    pkill rstp
    pkill misc
    pkill upgrade
    pkill igmp
    pkill voip
    pkill apm
    pkill midware
    pkill omci
    ;;
  powerdown)
    $0 stop
    if [ -n "$lan_port" ]; then
      ifdown "$lan_port"
    fi
    #power down GE PHY
    devmem 0xf1072004 32 0x00000800
    #power down GPON;
    devmem 0xf10184f4 32 0xe2000000
    #turn off some internal clocks
    #devmem 0xf101821c 32 0x140200c0
    #power down some internal memory
    #devmem 0xf1018218 32 0x00ff0100
    ;;
  restart|reload)
    $0 stop
    $0 start
    ;;
  *)
    echo "Usage: $0 {start|stop|restart|powerdown}"
    exit 1
esac
